from PyQt4  import QtCore, QtGui
from PyQt4.QtCore import pyqtSlot,pyqtSignal
from pyqtgraph.python2_3 import asUnicode
from pyqtgraph.WidgetGroup import WidgetGroup



import weakref 


class KChartViewBoxMenu(QtGui.QMenu):
    def __init__(self, view):
        QtGui.QMenu.__init__(self)
        
        self.view = weakref.ref(view)  ## keep weakref to view to avoid circular reference (don't know why, but this prevents the ViewBox from being collected)
        self.valid = False  ## tells us whether the ui needs to be updated
        self.viewMap = weakref.WeakValueDictionary()  ## weakrefs to all views listed in the link combos


        self.submenulist=[]
        
        # define menu operations
        MenusTable=[
            ["Time Periods", [["Daily Intervals","Time_1"],
                          ["Weekly Intervals","Time_7"],
                          ["Monthly Intervals","Time_30"],
                          ["Yearly Intervals","Time_365"]]
             ],
            ["Chart Settings",[]
             ],
            ["Studies",[["Add New Study","Study_Add"],
                          ["Configure Existing Study","Study_Config"],
                          ["Remove Existing Study Intervals","Study_Remove"]]
             ],
            ["Tools",[]
             ],
            ["Draw",[]
             ]
                    ]
        # add Menus
        for each_menu in MenusTable:
            PeriodSubMenu=QtGui.QMenu(each_menu[0])
            self.submenulist.append(PeriodSubMenu)
            m_mapper=QtCore.QSignalMapper(self)
            for each_action in each_menu[1]:            
                mAction=QtGui.QAction(each_action[0],PeriodSubMenu)
                m_mapper.setMapping(mAction,each_action[1])
                self.connect(mAction,QtCore.SIGNAL("triggered()"),m_mapper,QtCore.SLOT("map()"))
                PeriodSubMenu.addAction(mAction)
            m_mapper.mapped[QtCore.QString].connect(self.ExceuteAction)  
        

        

        self.updateState()
    def ExceuteAction(self,sAction):
        self.view().ExceuteMenuAction(sAction)

    def copy(self):
        m = QtGui.QMenu()
        for sm in self.subMenus():
            if isinstance(sm, QtGui.QMenu):
                m.addMenu(sm)
            else:
                m.addAction(sm)
        m.setTitle(self.title())
        return m

    def subMenus(self):
        if not self.valid:
            self.updateState()
        return self.submenulist 



        
    def updateState(self):
        ## Something about the viewbox has changed; update the menu GUI

 
 
        self.valid = True
        
        

from pyqtgraph.graphicsItems.ViewBox import ViewBox
        
